package apptoko.com;

import java.io.IOException;
import java.security.MessageDigest;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.RequestToken;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.graphics.Shader.TileMode;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import apptoko.com.adapter.ErrorHandler;
import apptoko.com.background.BackgroundTasks;
import apptoko.com.event.Event;
import apptoko.com.event.Event.CallGoogleAPISuccessEvent;
import apptoko.com.event.Event.CloseAfterLoginTwitter;
import apptoko.com.event.Event.FirstLoginEvent;
import apptoko.com.event.Event.LoginFailEvent;
import apptoko.com.event.Event.LoginTwitterFailEvent;
import apptoko.com.event.Event.LoginTwitterSuccessEvent;
import apptoko.com.event.Event.RegisterFailedEvent;
import apptoko.com.event.Event.RequestFailEvent;
import apptoko.com.event.Event.UpdateRegisterFailEvent;
import apptoko.com.event.Exception.GetGoogleTokenException;
import apptoko.com.event.Exception.GetGoogleTokenIOException;
import apptoko.com.event.Exception.GoogleApiIOException;
import apptoko.com.event.Exception.GoogleApiInterruptException;
import apptoko.com.event.Exception.GoogleLoginJSONException;
import apptoko.com.model.AccessToken;
import apptoko.com.model.UserInfo;
import apptoko.com.network.ProgressDialogManager;
import apptoko.com.util.Constants;
import apptoko.com.util.Utils;
import apptoko.com.validator.Form;
import apptoko.com.validator.Validate;
import apptoko.com.validator.validate.ConfirmValidate;
import apptoko.com.validator.validator.EmailValidator;
import apptoko.com.validator.validator.MinimumUsernameValidator;
import apptoko.com.validator.validator.NotEmptyValidator;
import apptoko.com.view.AlertDialogManager;
import apptoko.com.view.MyWebView;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.androidquery.AQuery;
import com.appota.asdk.commons.AccessTokenUtil;
import apptoko.com.R;
import com.devspark.appmsg.AppMsg;
import com.easy.facebook.android.apicall.GraphApi;
import com.easy.facebook.android.data.User;
import com.easy.facebook.android.error.EasyFacebookError;
import com.easy.facebook.android.facebook.FBLoginManager;
import com.easy.facebook.android.facebook.Facebook;
import com.easy.facebook.android.facebook.LoginListener;
import com.google.analytics.tracking.android.EasyTracker;
import com.google.android.gms.auth.GoogleAuthUtil;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.util.AsyncExecutor;
import de.greenrobot.event.util.AsyncExecutor.RunnableEx;

public class LoginActivity extends SherlockActivity implements OnClickListener, LoginListener {

	private EditText editUsername;
	private EditText editPassword;
	private String accessToken;
	private ProgressDialog pDialog;
	private AccountManager mAccountManager;
	private BackgroundTasks bgTask;
	private EventBus eventBus;
	private AQuery aQuery;
	private String googleToken;
	private UserInfo user;
	private Form form;
	private FBLoginManager fbLoginManager;
	private String FB_APP_ID;
	///
	
	// Twitter
    private static Twitter twitter;
    private static RequestToken requestToken;
    static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn";
    // Preference Constants
    public static String PREFERENCE_NAME = "twitter_oauth";
    public static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
    public static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
    public static final String PREF_USER_ID = "twitter_userid";
    // Shared Preferences
    private static SharedPreferences mSharedPreferences;
    public static final String TWITTER_CALLBACK_URL = "oauth://apptokotwitter";
 
    // Twitter oauth urls
    public static final String URL_TWITTER_AUTH = "auth_url";
    public static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
    public static final String URL_TWITTER_OAUTH_TOKEN = "oauth_token";
    private boolean goback=false;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		Log.e("Oncreate","onCreate");
		setTheme(R.style.Theme_Styled_Home);
		super.onCreate(savedInstanceState);
		if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            BitmapDrawable bg = (BitmapDrawable)getResources().getDrawable(R.drawable.action_bar_home);
            bg.setTileModeX(TileMode.REPEAT);
            getSupportActionBar().setBackgroundDrawable(bg);
        }
		setContentView(R.layout.activity_login);
		getSupportActionBar().setTitle(R.string.login);
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		// Shared Preferences
        mSharedPreferences = getApplicationContext().getSharedPreferences(
                "MyPref", 0);
		bgTask = new BackgroundTasks(this);
		EasyTracker.getInstance().setContext(this);
		aQuery = new AQuery(this);
		if(pDialog==null){
			pDialog=new ProgressDialog(this);
			pDialog.setMessage(getResources().getString(R.string.loading));
			pDialog.setCancelable(false);
		}
		eventBus = EventBus.getDefault();
		accessToken = Utils.getStaticAccessToken(this);
		editUsername = (EditText) findViewById(R.id.edt_input_user);
		editPassword = (EditText) findViewById(R.id.edt_input_password);
		if(getIntent()!=null && getIntent().getExtras()!=null){
			goback=getIntent().getExtras().getBoolean("goback");
		}
		form = new Form();
		Validate passValidate = new Validate(editPassword);
		passValidate.addValidator(new NotEmptyValidator(this));
		Validate userNameValidate = new Validate(editUsername);
		userNameValidate.addValidator(new NotEmptyValidator(this));
		form.addValidates(userNameValidate);
		form.addValidates(passValidate);
		aQuery.id(R.id.btn_sign_in).clicked(this);
		aQuery.id(R.id.btn_sign_up).clicked(this);
		aQuery.id(R.id.btn_login_gplus).clicked(this);
		aQuery.id(R.id.btn_login_facebook).clicked(this);
		aQuery.id(R.id.btnLoginTwitter).clicked(this);
		aQuery.id(R.id.forgot_password).clicked(this);
		///
		try {
			   PackageInfo info = getPackageManager().getPackageInfo(
			     "apptoko.com", PackageManager.GET_SIGNATURES);
			   for (Signature signature : info.signatures) {
			    MessageDigest md = MessageDigest.getInstance("SHA");
			    md.update(signature.toByteArray());
			    Log.e("KeyHash:",
			      Base64.encodeToString(md.digest(), Base64.DEFAULT));
			   }
			  } catch (Exception e) {
				  
			  }
				///
	}
	@Override
	protected void onNewIntent(Intent intent) {
		// TODO Auto-generated method stub
		super.onNewIntent(intent);
		Log.e("onNewIntent","onNewIntent");
		if(isWaitingForTwitter()){
			Uri uri = intent.getData();
	        if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
	            // oAuth verifier
	            String verifier = uri
	                    .getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);
	 
	            try {
	                // Get the access token
	                new GetTwitterAsync(verifier).execute();
	                mSharedPreferences.edit().putBoolean("twitter_wait", false).commit();
	            } catch (Exception e) {
	                // Check log for login errors
	                Log.e("Twitter Login Error", "> " + e.getMessage());
	            }
	        }
		}
		
	}
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		eventBus.register(this);
		com.facebook.AppEventsLogger.activateApp(this, getResources().getString(R.string.fb_app_id));
	}
	
//	public void onEventMainThread(GoogleTokenEvent event){
//		googleToken = event.getGoogleToken();
//		BackgroundTasks.callGoogleApi(googleToken);
//	}
	private enum LOGIN_TYPE{
		GOOGLE,
		FACEBOOK,
		TWITTER
	}
	private LOGIN_TYPE login_type=LOGIN_TYPE.GOOGLE;
	public void onEventMainThread(FirstLoginEvent event){
		showFirstUpdate();
	}
	private String email="";
	private String twitterToken="";
	private String twitterSecretToken="";
	private Dialog dialog;
	private Form formValidRegister;
	private EditText updateUsername;
	private EditText updatePassword;
	private EditText updateConfirmPass;
	private EditText updateEmail;
	private Button btn_update_info;
	private TextView noticeLbl;
	private Dialog showFirstUpdateDialog;
	public void showFirstUpdate(){
		showFirstUpdateDialog = new Dialog(this);
		LayoutInflater factory = LayoutInflater.from(this);
		final View view;
		view = factory.inflate(R.layout.firt_login, null);
		//
		formValidRegister = new Form();
		updateUsername = (EditText)view. findViewById(R.id.edt_signup_user);
		updatePassword = (EditText) view.findViewById(R.id.edt_signup_pass);
		updateConfirmPass = (EditText) view.findViewById(R.id.edt_signup_confirm_pass);
		updateEmail = (EditText)view.findViewById(R.id.edt_signup_email);
		noticeLbl=(TextView)view.findViewById(R.id.noticeLbl);
		LinearLayout emailLayout=(LinearLayout)view.findViewById(R.id.emailLayout);
		btn_update_info =(Button)view.findViewById(R.id.btn_update_info);
		Validate userNameValidate = new Validate(updateUsername);
		userNameValidate.addValidator(new NotEmptyValidator(this));
		btn_update_info.setOnClickListener(this);
		Validate passValidate = new Validate(updatePassword);
		passValidate.addValidator(new NotEmptyValidator(this));
		userNameValidate.addValidator(new MinimumUsernameValidator(this));
		Validate confirmValidate = new Validate(updateConfirmPass);
		confirmValidate.addValidator(new NotEmptyValidator(this));
		passValidate.addValidator(new MinimumUsernameValidator(this));
		confirmValidate.addValidator(new MinimumUsernameValidator(this));
		Validate emailValidate = new Validate(updateEmail);
		EmailValidator mailVal1 = new EmailValidator(this);
	    emailValidate.addValidator(mailVal1);
		emailValidate.addValidator(new NotEmptyValidator(this));
		
		ConfirmValidate confirmFields = new ConfirmValidate(updatePassword, updateConfirmPass);
		if(login_type==LOGIN_TYPE.TWITTER){
			formValidRegister.addValidates(emailValidate);
		}else{
			emailLayout.setVisibility(View.GONE);
		}
		formValidRegister.addValidates(userNameValidate);
		formValidRegister.addValidates(passValidate);
		formValidRegister.addValidates(confirmValidate);
		formValidRegister.addValidates(confirmFields);
		//
		showFirstUpdateDialog.setContentView(view);
		dialog=showFirstUpdateDialog;
		dialog.show();
		dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
	}
	public void onEventMainThread(UpdateRegisterFailEvent event){
		AppMsg.makeText(this, event.msg, AppMsg.STYLE_INFO, null).show();
	}
	private String msgGlobal;
	public void onEventMainThread(RequestFailEvent event){
		if(event.getErrorCode() == 21){
			showFirstUpdate();
//			AlertDialog.Builder am = new Builder(this);
//			am.setPositiveButton(event.msg!=null?event.msg:"Error: "+event.getErrorCode(), new DialogInterface.OnClickListener() {
//				
//				@Override
//				public void onClick(DialogInterface dialog, int which) {
//					// TODO Auto-generated method stub
//					dialog.dismiss();
//				}
//			}).show();
//			am.showButtonsDialog(, new DialogInterface.OnClickListener() {
//				@Override
//				public void onClick(DialogInterface dialog, int which) {
//					// TODO Auto-generated method stub
//					switch (which) {
////					case DialogInterface.BUTTON_POSITIVE:
////						Intent register = new Intent(LoginActivity.this, RegisterActivity.class);
////						if(isgg){
////							register.putExtra(Constants.GOOGLE_EMAIL, user.getEmail());
////							register.putExtra(Constants.GOOGLE_TOKEN, googleToken);
////						}else{
////							register.putExtra(Constants.FB_EMAIL, fbEmail);
////							register.putExtra(Constants.FB_TOKEN, fbToken);
////						}
////						register.putExtra(Constants.LOGIN_TYPE, isgg?"google":"facebook");
////						startActivity(register);
////						finish();
////						break;
//					case DialogInterface.BUTTON_NEGATIVE:
//						dialog.dismiss();
//						((AppStoreVnApplication) getApplication()).setLogin(false);
//						finish();
//						break;
//					}
//				}
//			});
		} else {
			AppMsg.makeText(this, R.string.error, AppMsg.STYLE_ALERT, null).show();
			ErrorHandler.getInstance().setContext(this).handleError(event.getErrorCode());
			msgGlobal=event.msg;
			if(showFirstUpdateDialog!=null&&showFirstUpdateDialog.isShowing()){
				noticeLbl.setText(msgGlobal);
			}
		}
		if(pDialog != null && pDialog.isShowing()){
			pDialog.dismiss();
		}
	}
	
	public void onEventMainThread(Event.LoginGoogleSuccessEvent event){
		if(pDialog != null && pDialog.isShowing()){
			pDialog.dismiss();
		}
		EasyTracker.getTracker().sendEvent(Constants.EVENT_ACTION, "Login", "LoginGoogleSuccess", Long.valueOf(1));
		AccessToken accessToken = event.getAccessToken();
		getSharedPreferences(Constants.SHARED_NAME, MODE_PRIVATE).edit().putString(Constants.ACCESS_TOKEN, event.getAccessToken().getAccessToken()).commit();
		getSharedPreferences(Constants.SHARED_NAME, MODE_PRIVATE).edit().putString(Constants.ACCESS_TOKEN_EXPIRES, event.getAccessToken().getExpiresIn()).commit();
		getSharedPreferences(Constants.SHARED_NAME, MODE_PRIVATE).edit().putBoolean(Constants.LOGIN, true).commit();
		getSharedPreferences(Constants.SHARED_NAME, MODE_PRIVATE).edit().putString(Constants.REFRESH_TOKEN_KEY, event.getAccessToken().getRefreshToken()).commit();
		AccessTokenUtil.getInstance().init(this).saveAccessTokenStr(accessToken.getAccessToken());
		AccessTokenUtil.getInstance().init(this).saveAccessTokenExpires(accessToken.getExpiresIn());
		((AppStoreVnApplication) getApplication()).setAccessToken(accessToken.getAccessToken());
		((AppStoreVnApplication) getApplication()).setLogin(true);
		AppMsg.makeText(this, R.string.login_success, AppMsg.STYLE_INFO, null).show();
		Intent nofityIntent = new Intent("LOGGEDIN_AND_RELOAD");
		nofityIntent.putExtra("tk", accessToken.getAccessToken());
		this.sendBroadcast(nofityIntent);
		if(goback){
			setResult(RESULT_OK,getIntent().putExtra("tk", accessToken.getAccessToken()));
		}
		finish();
	}
	public void onEventMainThread(Event.LoginFacebookSuccessEvent event){
		EasyTracker.getTracker().sendEvent(Constants.EVENT_ACTION, "Login", "LoginFacebookSuccess", Long.valueOf(1));
		AccessToken accessToken = event.getAccessToken();
		getSharedPreferences(Constants.SHARED_NAME, MODE_PRIVATE).edit().putString(Constants.ACCESS_TOKEN, event.getAccessToken().getAccessToken()).commit();
		getSharedPreferences(Constants.SHARED_NAME, MODE_PRIVATE).edit().putString(Constants.ACCESS_TOKEN_EXPIRES, event.getAccessToken().getExpiresIn()).commit();
		getSharedPreferences(Constants.SHARED_NAME, MODE_PRIVATE).edit().putBoolean(Constants.LOGIN, true).commit();
		getSharedPreferences(Constants.SHARED_NAME, MODE_PRIVATE).edit().putString(Constants.REFRESH_TOKEN_KEY, event.getAccessToken().getRefreshToken()).commit();
		AccessTokenUtil.getInstance().init(this).saveAccessTokenStr(accessToken.getAccessToken());
		AccessTokenUtil.getInstance().init(this).saveAccessTokenExpires(accessToken.getExpiresIn());
		((AppStoreVnApplication) getApplication()).setAccessToken(accessToken.getAccessToken());
		((AppStoreVnApplication) getApplication()).setLogin(true);
		AppMsg.makeText(this, R.string.login_success, AppMsg.STYLE_INFO, null).show();
		Intent nofityIntent = new Intent("LOGGEDIN_AND_RELOAD");
		nofityIntent.putExtra("tk", accessToken.getAccessToken());
		this.sendBroadcast(nofityIntent);
		if(goback){
			setResult(RESULT_OK,getIntent().putExtra("tk", accessToken.getAccessToken()));
		}
		finish();
		pDialog.dismiss();
	}
	
	public void onEventMainThread(Event.LoginSuccessEvent event){
		EasyTracker.getTracker().sendEvent(Constants.EVENT_ACTION, "Login", "LoginSuccess", Long.valueOf(1));
		((AppStoreVnApplication) getApplication()).setAccessToken(event.getAccessToken().getAccessToken());
		((AppStoreVnApplication) getApplication()).setLogin(true);
		SharedPreferences pref = getSharedPreferences(Constants.SHARED_NAME, MODE_PRIVATE);
		pref.edit().putString(Constants.ACCESS_TOKEN, event.getAccessToken().getAccessToken()).commit();
		pref.edit().putString(Constants.ACCESS_TOKEN_EXPIRES, event.getAccessToken().getExpiresIn()).commit();
		pref.edit().putString(Constants.REFRESH_TOKEN_KEY, event.getAccessToken().getRefreshToken()).commit();
		pref.edit().putBoolean(Constants.LOGIN, true).commit();
		AccessTokenUtil.getInstance().init(this).saveAccessTokenStr(event.getAccessToken().getAccessToken());
		AccessTokenUtil.getInstance().init(this).saveAccessTokenExpires(event.getAccessToken().getExpiresIn());
		if(pDialog != null){
			pDialog.dismiss();
		}
		Intent nofityIntent = new Intent("LOGGEDIN_AND_RELOAD");
		nofityIntent.putExtra("tk", event.getAccessToken().getAccessToken());
		this.sendBroadcast(nofityIntent);
		if(goback){
			setResult(RESULT_OK,getIntent().putExtra("tk", event.getAccessToken().getAccessToken()));
		}
		finish();
	}
	
	public void onEventMainThread(final Event.RegisterSuccessEvent event){
		EasyTracker.getTracker().sendEvent(Constants.EVENT_ACTION, "Login", "LoginSuccess", Long.valueOf(1));
		((AppStoreVnApplication) getApplication()).setAccessToken(event.getAccessToken().getAccessToken());
		((AppStoreVnApplication) getApplication()).setLogin(true);
		SharedPreferences pref = getSharedPreferences(Constants.SHARED_NAME, MODE_PRIVATE);
		pref.edit().putString(Constants.ACCESS_TOKEN, event.getAccessToken().getAccessToken()).commit();
		pref.edit().putString(Constants.ACCESS_TOKEN_EXPIRES, event.getAccessToken().getExpiresIn()).commit();
		pref.edit().putString(Constants.REFRESH_TOKEN_KEY, event.getAccessToken().getRefreshToken()).commit();
		pref.edit().putBoolean(Constants.LOGIN, true).commit();
		AccessTokenUtil.getInstance().init(this).saveAccessTokenStr(event.getAccessToken().getAccessToken());
		AccessTokenUtil.getInstance().init(this).saveAccessTokenExpires(event.getAccessToken().getExpiresIn());
		if(pDialog != null){
			pDialog.dismiss();
		}
		
		if(login_type==LOGIN_TYPE.TWITTER){
			AlertDialog.Builder builder=new Builder(LoginActivity.this);
			String msg=String.format(getResources().getString(R.string.register_success), updateEmail.getText().toString());
			builder.setMessage(msg).setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					dialog.dismiss();
					Intent nofityIntent = new Intent("LOGGEDIN_AND_RELOAD");
					nofityIntent.putExtra("tk", event.getAccessToken().getAccessToken());
					LoginActivity.this.sendBroadcast(nofityIntent);
					if(goback){
						setResult(RESULT_OK,getIntent().putExtra("tk", event.getAccessToken().getAccessToken()));
					}
					finish();
				}
			});
			AlertDialog dialog=builder.create();
			dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.WHITE));
			dialog.setCancelable(false);
			dialog.show();
		}else{
			Intent nofityIntent = new Intent("LOGGEDIN_AND_RELOAD");
			nofityIntent.putExtra("tk", event.getAccessToken().getAccessToken());
			this.sendBroadcast(nofityIntent);
			if(goback){
				setResult(RESULT_OK,getIntent().putExtra("tk", event.getAccessToken().getAccessToken()));
			}
			finish();
		}
		
	}
	
	public void onEventMainThread(LoginFailEvent event){
		if(pDialog!=null&&pDialog.isShowing()){
			pDialog.dismiss();
		}
		AppMsg.makeText(this, event.getErrorCode(), AppMsg.STYLE_ALERT, null).show();
	}
	
	public void onEventMainThread(RegisterFailedEvent event){
		if(pDialog!=null&&pDialog.isShowing()){
			pDialog.dismiss();
		}
		AppMsg.makeText(this, event.getErrorCode(), AppMsg.STYLE_ALERT, null).show();
		msgGlobal=event.getErrorCode();
		if(showFirstUpdateDialog!=null&&showFirstUpdateDialog.isShowing()){
			noticeLbl.setText(msgGlobal);
		}
	}
	@Override
    public void onStart() {
        super.onStart();
        EasyTracker.getTracker().sendView("Login");
    }
	
	public void onEventMainThread(CallGoogleAPISuccessEvent event){
		user = event.getUser();
		accessToken = Utils.getStaticAccessToken(this);
		email=user.getEmail();
		bgTask.googleLogIn(accessToken, googleToken, user.getEmail(),getResources().getString(R.string.lang));
		System.err.println("Google token: " + googleToken);
	}
	
	public void onEventMainThread(GetGoogleTokenIOException ioe){
		Toast.makeText(this, R.string.error, Toast.LENGTH_SHORT).show();
		pDialog.dismiss();
	}
	
	public void onEventMainThread(GetGoogleTokenException e){
		Toast.makeText(this, R.string.google_signin_request, Toast.LENGTH_SHORT).show();
		pDialog.dismiss();
	}
	
	public void onEventMainThread(GoogleApiIOException ioe){
		Toast.makeText(this, R.string.error, Toast.LENGTH_SHORT).show();
		pDialog.dismiss();
	}
	
	public void onEventMainThread(GoogleApiInterruptException ioe){
		Toast.makeText(this, R.string.error, Toast.LENGTH_SHORT).show();
		pDialog.dismiss();
	}
	
	public void onEventMainThread(GoogleLoginJSONException je){
		Toast.makeText(this, R.string.error, Toast.LENGTH_SHORT).show();
		pDialog.dismiss();
	}
    
    @Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		eventBus.unregister(this);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case android.R.id.home:
			setResult(RESULT_CANCELED);
			finish();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	private Account[] getAccounts() {
	    mAccountManager = AccountManager.get(this);
	    Account[] accounts = mAccountManager.getAccountsByType(GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE);
	    return accounts;
	}
	
	private String[] getAccountNames(Account[] accounts){
	    String[] names = new String[accounts.length];
	    for (int i = 0; i < names.length; i++) {
	        names[i] = accounts[i].name;
	    }
	    return names;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btn_sign_in:
			if(form.validate()){
				pDialog = ProgressDialogManager.showProgressDialog(this, R.string.login_ing);
				accessToken = Utils.getStaticAccessToken(this);
				bgTask.logIn(accessToken, editUsername.getText().toString(), editPassword.getText().toString(),getResources().getString(R.string.lang));
			}else{
				if(!TextUtils.isEmpty(editUsername.getText().toString())&&TextUtils.isEmpty(editPassword.getText().toString())){
					editPassword.requestFocus();
				}
			}
			break;
		case R.id.btn_sign_up:
			Intent i = new Intent(LoginActivity.this, RegisterActivity.class);
			i.putExtra(Constants.LOGIN_TYPE, "normal");
			startActivity(i);
			break;
		case R.id.btn_login_gplus:
			login_type=LOGIN_TYPE.GOOGLE;
			AlertDialogManager am = new AlertDialogManager(this);
			final Account[] accs = getAccounts();
 			final String[] accounts = getAccountNames(accs);
			final String scopes = "oauth2:https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile";
			am.showDialogWithItems(R.string.choose_google_account, accounts, new DialogInterface.OnClickListener() {
				@Override 
				public void onClick(DialogInterface dialog, int which) {
					pDialog = ProgressDialogManager.showProgressDialog(LoginActivity.this, R.string.loading);
					Bundle options = new Bundle();
					mAccountManager.getAuthToken(
						accs[which],                     // Account retrieved using getAccountsByType()
					    scopes,            // Auth scope
					    options,                        // Authenticator-specific options
					    LoginActivity.this,                           // Your activity
					    new OnTokenAcquired(),          // Callback called when a token is successfully acquired
					    new Handler());    // Callback called if an error occurs
				}
			});
			break;
		case R.id.btn_login_facebook:
			login_type=LOGIN_TYPE.FACEBOOK;
			konnectFacebook();
			break;
		case R.id.btnLoginTwitter:
			login_type=LOGIN_TYPE.TWITTER;
			if(pDialog!=null&&!pDialog.isShowing()){
				pDialog.show();
			}
//			mSharedPreferences.edit().putBoolean("twitter_wait", true).commit();
			new GetTwitterAsync(null).execute();
			
			break;
		case R.id.forgot_password:
			Intent forgot = new Intent(Intent.ACTION_VIEW);
			forgot.setData(Uri.parse(Constants.FORGOT_PASSWORD_URL));
			startActivity(forgot);
			break;
		case R.id.btn_update_info:
			if(formValidRegister.validate()){
				if(pDialog!=null&&!pDialog.isShowing()){
					pDialog.show();
				}
				Log.e("here","here");
				if(login_type==LOGIN_TYPE.GOOGLE){
					bgTask.registerGoogle(accessToken, googleToken, updateUsername.getText().toString(), updatePassword.getText().toString(),email,getResources().getString(R.string.lang));
				}else if(login_type==LOGIN_TYPE.TWITTER){
					bgTask.registerTwitter(accessToken, twitterToken,twitterSecretToken, updateUsername.getText().toString(), updatePassword.getText().toString(),updateEmail.getText().toString(),getResources().getString(R.string.lang));
				}else{
					bgTask.registerFacebook(accessToken, fbToken, updateUsername.getText().toString(), updatePassword.getText().toString(),email,getResources().getString(R.string.lang));
				}
//				bgTask.updateregister(accessToken, updateUsername.getText().toString(), updatePassword.getText().toString(), email,getResources().getString(R.string.lang));
			}
			break;
		}
	}
	private class GetTwitterAsync extends AsyncTask<Void, Void, Void>{
		private String verifier;
		public GetTwitterAsync(String verifier){
			this.verifier=verifier;
		}
		@Override
		protected Void doInBackground(Void... params) {
			loginToTwitter(verifier);
			return null;
		}
		
	}
	private void loginToTwitter(String verifier) {
        // Check if already logged in
		if(verifier!=null){
			try{
			twitter4j.auth.AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
			Log.e("tVerifier",verifier);
            Editor e = mSharedPreferences.edit();
            e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
            e.putString(PREF_KEY_OAUTH_SECRET,
                    accessToken.getTokenSecret());
            e.putLong(PREF_USER_ID, accessToken.getUserId());
            e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
            e.commit();
            twitterToken=accessToken.getToken();
            twitterSecretToken=accessToken.getTokenSecret();
			bgTask.loginTwitter(this.accessToken, accessToken.getToken(), accessToken.getTokenSecret(),getResources().getString(R.string.lang));
			}catch(Exception ex){}
		}else{
//			ConfigurationBuilder builder = new ConfigurationBuilder();
//            builder.setOAuthConsumerKey(Constants.TWITTER_CONSUMER_KEY);
//            builder.setOAuthConsumerSecret(Constants.TWITTER_CONSUMER_SECRET);
//            Configuration configuration = builder.build();
//            
//            TwitterFactory factory = new TwitterFactory(configuration);
//            twitter = factory.getInstance();
// 
//            try {
//                requestToken = twitter
//                        .getOAuthRequestToken(TWITTER_CALLBACK_URL);
//                this.startActivity(new Intent(Intent.ACTION_VIEW, Uri
//                        .parse(requestToken.getAuthenticationURL())));
//            } catch (TwitterException e) {
//                e.printStackTrace();
//            }
			///
			twitter = new TwitterFactory().getInstance();
            requestToken = null;
            try
            {
            	twitter.setOAuthConsumer(Constants.TWITTER_CONSUMER_KEY,Constants.TWITTER_CONSUMER_SECRET );
                requestToken = twitter.getOAuthRequestToken(TWITTER_CALLBACK_URL);
                Intent loginIntent = new Intent(this, MyWebView.class);
                loginIntent.putExtra("url", requestToken.getAuthenticationURL());
                startActivityForResult(loginIntent, 222);
            }
            catch (Exception e)
            {
                e.printStackTrace();
                runOnUiThread(new Runnable() {
					
					@Override
					public void run() {
						if(pDialog!=null &&pDialog.isShowing()){
							pDialog.dismiss();
						}
						AppMsg.makeText(LoginActivity.this, getResources().getString(R.string.error)+"(Twitter Error)", AppMsg.STYLE_ALERT, null).show();
					}
				});
            }
		}
    }
	private class OnTokenAcquired implements AccountManagerCallback<Bundle> {
	    @Override
	    public void run(AccountManagerFuture<Bundle> result) {
	        Bundle bundle;
			try {
				Intent launch = (Intent) result.getResult().get(AccountManager.KEY_INTENT);
		        if (launch != null) {
		            startActivityForResult(launch, Constants.LOGIN_GOOGLE_REQUEST_CODE);
		            return;
		        }
				bundle = result.getResult();
				googleToken = bundle.getString(AccountManager.KEY_AUTHTOKEN);
				BackgroundTasks.callGoogleApi(googleToken);
			} catch (OperationCanceledException e) {
				e.printStackTrace();
			} catch (AuthenticatorException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
	    }
	}
	
	private void konnectFacebook(){
		String permissions[] = {"email", "read_stream","publish_stream", "read_friendlists"};
		FB_APP_ID = getResources().getString(R.string.fb_app_id);
		fbLoginManager = new FBLoginManager(this, R.layout.activity_login, FB_APP_ID, permissions);
		if(fbLoginManager.existsSavedFacebook()){
			fbLoginManager.loadFacebook();
		} else {
			fbLoginManager.login();
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data){
		if(requestCode == Constants.LOGIN_GOOGLE_REQUEST_CODE && resultCode == RESULT_OK){
			Bundle bundle = data.getExtras();
			googleToken = bundle.getString(AccountManager.KEY_AUTHTOKEN);
			//pDialog = ProgressDialogManager.showProgressDialog(LoginActivity.this, R.string.loading);
			BackgroundTasks.callGoogleApi(googleToken);
		} else if(resultCode == RESULT_OK){
			Log.e("ActivityResult","Result_Ok");
			if(data!=null){
				Log.e("LoginActivityResult","Result_Ok & data intent != null");
				if(fbLoginManager!=null){
					if(data.hasExtra("expires_in")&&data.hasExtra("access_token")){
						fbLoginManager.loginSuccess(data);
					}else if(data.hasExtra("oauth_verifier")){
						Log.e("LoginActivityResult","Get oauth_verifier: "+data.getExtras().getString("oauth_verifier"));
					}
				}else{
					if(data.hasExtra("oauth_verifier")){
						Log.e("LoginActivityResult","Get oauth_verifier: "+data.getExtras().getString("oauth_verifier"));
						new GetTwitterAsync(data.getExtras().getString("oauth_verifier")).execute();
					}
					Log.e("LoginActivityResult","Result_Ok & data intent != null & fbLoginManager = NULL");
				}
				
			}else{
				Log.e("ActivityResult","Result_Ok & data intent = NULL");
				AppMsg.makeText(this, getResources().getString(R.string.login_fail)+"(01)", AppMsg.STYLE_ALERT, null).show();
				if(pDialog!=null && pDialog.isShowing()){
					pDialog.dismiss();
				}
			}
		}else if(resultCode == Activity.RESULT_CANCELED){
			if(pDialog!=null && pDialog.isShowing()){
				pDialog.dismiss();
			}
		}else{
			AppMsg.makeText(this, getResources().getString(R.string.login_fail)+"(00)", AppMsg.STYLE_ALERT, null).show();
			if(pDialog!=null && pDialog.isShowing()){
				pDialog.dismiss();
			}
			Log.e("ActivityResult","Result_NOT_Ok");
		}
		
	}
	private String fbToken,fbEmail;
	@Override
	public void loginSuccess(Facebook facebook) {
		// TODO Auto-generated method stub
		fbToken = facebook.getAccessToken();
		System.err.println(fbToken);
		final GraphApi graphApi = new GraphApi(facebook);
		pDialog = ProgressDialogManager.showProgressDialog(LoginActivity.this, R.string.loading);
			AsyncExecutor.create().execute(new RunnableEx() {
				@Override
				public void run() {
					// TODO Auto-generated method stub
					User fbUser;
					try {
						fbUser = graphApi.getMyAccountInfo();
						fbEmail = fbUser.getEmail();
						accessToken = Utils.getStaticAccessToken(LoginActivity.this);
						email=fbEmail;
						bgTask.loginFacebook(accessToken, fbToken, fbEmail,getResources().getString(R.string.lang));
					} catch (EasyFacebookError e) {
						e.printStackTrace();
						AppMsg.makeText(LoginActivity.this, e.getMessage(), AppMsg.STYLE_ALERT, null).show();
					}
				}
			});
	}

	@Override
	public void logoutSuccess() {
		// TODO Auto-generated method stub
		AppMsg.makeText(this, R.string.logout, AppMsg.STYLE_ALERT, null).show();
	}

	@Override
	public void loginFail() {
		// TODO Auto-generated method stub
		AppMsg.makeText(this, R.string.login_fb_fail, AppMsg.STYLE_ALERT, null).show();
	}
	private boolean isWaitingForTwitter() {
        // return twitter login status from Shared Preferences
        return mSharedPreferences.getBoolean("twitter_wait", false);
    }
	
	public void onEventMainThread(CloseAfterLoginTwitter event){
		Intent returns=new Intent(this, HomeActivity.class);
		startActivityIfNeeded(returns, 1223);
		finish();
	}
	
	public void onEventMainThread(final LoginTwitterSuccessEvent event){
		Log.e("LoginTwitterSuccessEvent", "LoginTwitterSuccessEvent");
		if(pDialog!=null && pDialog.isShowing()){
			pDialog.dismiss();
		}
		///
		EasyTracker.getTracker().sendEvent(Constants.EVENT_ACTION, "Login", "LoginTwitterSuccess", Long.valueOf(1));
		getSharedPreferences(Constants.SHARED_NAME, MODE_PRIVATE).edit().putBoolean(Constants.LOGIN, true).commit();
		getSharedPreferences(Constants.SHARED_NAME, MODE_PRIVATE).edit().putString(Constants.ACCESS_TOKEN, event.accessToken).commit();
		getSharedPreferences(Constants.SHARED_NAME, MODE_PRIVATE).edit().putString(Constants.ACCESS_TOKEN_EXPIRES, event.expires_in).commit();
		AccessTokenUtil.getInstance().init(this).saveAccessTokenStr(event.accessToken);
		AccessTokenUtil.getInstance().init(this).saveAccessTokenExpires(String.valueOf(event.expires_in));
		((AppStoreVnApplication) getApplication()).setAccessToken(event.accessToken);
		((AppStoreVnApplication) getApplication()).setLogin(true);
		AppMsg.makeText(this, R.string.login_success, AppMsg.STYLE_INFO, null).show();
		if(goback){
			setResult(RESULT_OK,getIntent().putExtra("tk", event.accessToken));
		}
		//show dialog
		if(event.status){
			eventBus.post(new Event.LoginEvent(event.accessToken));
			finish();
		}else{
			AlertDialog.Builder builder=new Builder(LoginActivity.this);
			builder.setMessage(getResources().getString(R.string.login_not_active_success)).setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					eventBus.post(new Event.LoginEvent(event.accessToken));
					dialog.dismiss();
					finish();
				}
			});
			AlertDialog dialog=builder.create();
			dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.WHITE));
			dialog.setCancelable(false);
			dialog.show();
		}
				
	}
	
	public void onEventMainThread(LoginTwitterFailEvent event){
		AppMsg.makeText(this, getResources().getString(R.string.login_fail)+"("+event.error_code+")", AppMsg.STYLE_ALERT, null).show();
		if(pDialog!=null && pDialog.isShowing()){
			pDialog.dismiss();
		}
	}
}
